// 负责管理跟账户相关的全局数据
import  type { UserInfo,AccountType }  from '../../model/user'
import { userLogin}  from '../../api/user'
interface State{
	uinfo:UserInfo|null
}
interface ErrorType{
	data?:{
		code:number
		error:string
	}
}
export default {
	namespaced:true,//开启局部调用
	state:()=>{
		return {uinfo:null}
	},
	// state:()=>({uinfo:null}),  //简写
	mutations:{
		loginSuccess(state:State,info:UserInfo){
			state.uinfo=info
			uni.setStorage({
				key:'uinfo',
				data:info
			})
		},
		//用户刷新后，使用本地用户信息
		init(state:State,info:UserInfo){
			state.uinfo=info
		}
	},
	actions:{
		async loginActions(context:any,{username,password}:AccountType){
	    	let title='登录成功'
			try{
				let res =await userLogin(username,password)
				console.log('登录成功',res);
				context.commit('loginSuccess',res.data)
				uni.switchTab({
					url:"/pages/home/home"
				})
			}catch(e){
				title=(e as ErrorType).data!.error
				console.log('登录失败',e);
			}
			uni.showToast({
				title,
				icon:'none'
			})
		}
	}
}